//===============================================================================
// Microsoft patterns & practices
// Guidance Explorer Offline Client
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================

using System;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using GuidanceExplorer;
//using GuidanceExplorer.WorkItems;
using GuidanceExplorer.Controls;
using GuidanceExplorer.Model;
using GuidanceExplorer.Services;
using GuidanceExplorer.Views;
using GuidanceExplorerAddIn.Controls;
using GuidanceExplorerAddIn.Services;

namespace GuidanceExplorerAddIn.Views
{
    public partial class GuidanceItemMetadata : UserControl
    {

        #region Private members

        private GEController _controller;
        /// <summary>
        /// The main model service instance.
        /// </summary>
        private IAddinModelStorageService _modelService;

        /// <summary>
        /// The HTML rendering service for the guidance items.
        /// </summary>
        private IHtmlRenderService _htmlRenderService;

        /// <summary>
        /// The WinForm rendering service for the guidance items.
        /// </summary>
        private IWinFormsRenderService _winFormsRenderService;

        /// <summary>
        /// The guidance item that is being edited.
        /// </summary>
        private GuidanceItemFileReference _guidanceItem;

        /// <summary>
        /// The library currently selected.
        /// </summary>
        private LibraryNode _library;

        /// <summary>
        /// The view node to add a new item
        /// </summary>
        private ViewNode _view;

		/// <summary>
		/// The checkList node to add a new item
		/// </summary>
		private ChecklistNode _checkList;

        private bool _exitHandled = false;

        /// <summary>
        /// The id of the guidance item chosen to edit
        /// </summary>
        private string _originalItemId; 

        #endregion

        /// <summary>
        /// The main model service instance.
        /// </summary>
        public IAddinModelStorageService ModelService
        {
            set 
            { 
                _modelService = value;
                htmlEditControl.ModelService = _modelService;
            }
        }
        /// <summary>
        /// The main controller instance.
        /// </summary>
        public GEController Controller
        {
            set 
            { 
                _controller = value;
                htmlEditControl.Controller = _controller;
            }
        }

        /// <summary>
        /// The HTML rendering service for the guidance items.
        /// </summary>
        public IHtmlRenderService HtmlRenderService
        {
            set 
            {
                _htmlRenderService = value; 
                htmlEditControl.HtmlRenderService = _htmlRenderService; 
            }
        }

        /// <summary>
        /// The WinForms rendering service for the guidance items.
        /// </summary>
        public IWinFormsRenderService WinFormsRenderService
        {
            set { _winFormsRenderService = value; }
        }

        /// <summary>
        /// Default constructor.
        /// </summary>
        public GuidanceItemMetadata()
        {
            InitializeComponent();
        }


        /// <summary>
        /// Set the guidance item that will be edited.
        /// </summary>
        /// <param name="guidanceItem"></param>
        /// <param name="readProtection"></param>
        public void SetGuidanceItem(LibraryNode library, GuidanceItemFileReference guidanceItem, ReadProtection readProtection, ViewNode view, ChecklistNode checkList)
        {
            _library = library;
            _guidanceItem = guidanceItem;
            _originalItemId = _guidanceItem.Id;
            _view = view;
			_checkList = checkList;
            _txtCSS.Text = _guidanceItem.CSSFile;
            _txtFile.Text = _guidanceItem.FileName;//Path.Combine(_modelService.Guidance.SolutionViews.SolutionGuidancesFolder.FullName, _guidanceItem.FileName);

            //if it is a solution item
            if (_library == null && ((File.Exists(_guidanceItem.FullFileName) ||  _view!= null && _view.ModelInstance.CopyItemsByValue)))              
            {
                btnSave.Enabled = true;
            }
			else if (_library == null && ((File.Exists(_guidanceItem.FullFileName) || _checkList != null && _checkList.ModelInstance.CopyItemsByValue)))
			{
				btnSave.Enabled = true;
			}
			else if (_library == null || _library.ModelInstance.ReadProtection == ReadProtection.ReadOnly)
			{
				btnSave.Enabled = false;
				_guidanceItem = _guidanceItem.Clone();
				_guidanceItem.FileName = ModelStorageService.LibraryFolder;
				_guidanceItem.Id = Guid.NewGuid().ToString();
			}
            Type guidanceItemType = _guidanceItem.GetType();
            float maxFirstCol = 0;
            float maxSecondCol = 0;

            //Display the items in the group box
            int row = -1, col = tableLayoutPanel.ColumnCount;
            txtTitle.Text = guidanceItem.Title;
            tableLayoutPanel.RowCount = guidanceItem.CustomData.Count - 2; //Remove the custom data for the title and the author
            foreach (Field field in guidanceItem.GuidanceType.Fields.Values)
            {
                //Skip non editable fields.
                if (!field.Editable)
                {
                    continue;
                }

                //Skip the author field
                if (field.Name == "Author")
                {
                    if (guidanceItem.CustomData.ContainsKey(field.Name))
                    {
                        txtAuthor.Text = guidanceItem.CustomData[field.Name];
                    }
                    continue;
                }

                bool propertyFound = false;
                string value = string.Empty;
                foreach (PropertyInfo property in guidanceItemType.GetProperties())
                {
                    if (property.Name == field.Name)
                    {
                        //If the property has been found, then set it's value.
                        value = (string)property.GetValue(_guidanceItem, null);
                        propertyFound = true;
                        break;
                    }
                }

                //If the property was not found, then use the custom data.
                if (!propertyFound)
                {
                    if (guidanceItem.CustomData.ContainsKey(field.Name))
                    {
                        value = guidanceItem.CustomData[field.Name];
                    }
                }

                //Reset column count place.
                if (col == tableLayoutPanel.ColumnCount)
                {
                    col = 0;
                }

                //Set the row position
                if (col == 0)
                {
                    row++;
                }

                //Create the label for the custom data value
                Label customDataLabel = new Label();
                customDataLabel.Name = "lbl" + field.Name;
                customDataLabel.Text = "&" + field.Caption;
                customDataLabel.Dock = DockStyle.Fill;
                customDataLabel.AutoSize = true;
                tableLayoutPanel.Controls.Add(customDataLabel);
                tableLayoutPanel.SetCellPosition(customDataLabel, new TableLayoutPanelCellPosition(col, row));
                float textSize = Graphics.FromHwnd(customDataLabel.Handle).MeasureString(customDataLabel.Text, customDataLabel.Font).Width;
                if (col == 0 && textSize > maxFirstCol)
                {
                    maxFirstCol = textSize;
                }
                else if (col == 3 && textSize > maxSecondCol)
                {
                    maxSecondCol = textSize;
                }

                col++;

                //Create the control for the custom data value.
                if (field.Type == FieldType.Text)
                {
                    TextBox customData = new TextBox();
                    customData.Name = "txt" + field.Name;
                    customData.Text = value;
                    customData.Width = 200;
                    customData.Dock = DockStyle.Fill;
                    tableLayoutPanel.Controls.Add(customData);
                    tableLayoutPanel.SetCellPosition(customData, new TableLayoutPanelCellPosition(col++, row));
                }
                else if (field.Type == FieldType.Combo)
                {
                    ComboBox customData = new ComboBox();
                    customData.Name = "txt" + field.Name;
                    customData.Width = 200;
                    customData.Dock = DockStyle.Fill;
                    _winFormsRenderService.PopulateCombo(customData, field, _modelService.Guidance.Items);
                    if (!field.Distinct)
                    {
                        if (field.Values != null)
                        {
                            foreach (string val in field.Values)
                            {
                                if (!customData.Items.Contains(val))
                                {
                                    customData.Items.Add(val);
                                }
                            }
                        }
                    }

                    if (field.Editable)
                    {
                        customData.DropDownStyle = ComboBoxStyle.DropDown;
                    }
                    else
                    {
                        customData.DropDownStyle = ComboBoxStyle.DropDownList;
                    }

                    customData.Text = value;
                    customData.SelectedText = string.Empty;
                    tableLayoutPanel.Controls.Add(customData);
                    tableLayoutPanel.SetCellPosition(customData, new TableLayoutPanelCellPosition(col++, row));
                }
                else
                {
                    throw new NotImplementedException();
                }

                if (col == 2)
                {
                    col++;
                }
            }

            //Update the rowcount to make calculations.
            if (row == 0)
            {
                row++;
            }

            //Calculate the height of the controls
            customDataContainer.Height = 25 * (row + 2);
            htmlEditControl.Height = Height - customDataContainer.Height - 80 - pnlPaths.Height - 30;
            customDataContainer.Top = Height - customDataContainer.Height - 25 - pnlPaths.Height - 30;
            pnlPaths.Top = customDataContainer.Top + customDataContainer.Height + 15;
            btnCancel.Top = btnEdit.Top = btnSave.Top = btnSaveAs.Top = pnlPaths.Top + pnlPaths.Height + 5;

            tableLayoutPanel.ColumnStyles[0].Width = maxFirstCol + 10;
            tableLayoutPanel.ColumnStyles[3].Width = maxSecondCol + 10;

            //Set buttons in the parent form.
            Form parent = Parent as Form;
            if (parent != null)
            {
                parent.CancelButton = btnCancel;
                if (readProtection == ReadProtection.ReadOnly)
                {
                    parent.AcceptButton = btnEdit;
                }
                else
                {
                    parent.AcceptButton = null;
                }
            }

            //Render edition control.
            htmlEditControl.Initialize(guidanceItem, readProtection);

            //Prepare the buttons depending on the protection mode.
            if (readProtection == ReadProtection.ReadOnly)
            {
                btnSave.Visible = false;
                btnSaveAs.Visible = false;
                btnEdit.Visible = true;
                btnEdit.Location = btnSaveAs.Location;
            }
            else if (readProtection == ReadProtection.ReadWrite)
            {
                btnEdit_Click(this, EventArgs.Empty);
            }

            txtTitle.Focus();
        }

        /// <summary>
        /// Called when the Cancel button is pressed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            _exitHandled = true;
            DialogResult res = DialogResult.No;
            if (HasItemChanged())
            {
                res = MessageBox.Show(this, Messages.ITEM_CHANGED_SAVE_CONFIRMATION, Messages.WARNING,
                    MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
            }

            if (res == DialogResult.No)
            {
                _controller.CloseToolWindow(_controller.FormatGuid(_originalItemId));
				_controller.TreeView.SelectedNode = null;
            }
            else if (res == DialogResult.Yes)
            {
                //If this is a new file
                if (!File.Exists(_guidanceItem.FullFileName))
                {
                    btnSaveAs_Click(null, null);
                }
                else
                {
                    btnSave_Click(null, null);
                }
            }
            else
            {
                _exitHandled = false;
            }
        }

        /// <summary>
        /// Called when the Edit button is pressed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEdit_Click(object sender, EventArgs e)
        {
            htmlEditControl.ReadProtection = ReadProtection.ReadWrite;
            btnSave.Visible = true;
            btnSaveAs.Visible = true;
            btnEdit.Visible = false;
            Form parent = Parent as Form;
            if (parent != null)
            {
                parent.AcceptButton = null;
            }
        }

        /// <summary>
        /// Returns whether the item has changed or not
        /// </summary>
        /// <returns></returns>
        private bool HasItemChanged()
        {
            Type guidanceItemType = _guidanceItem.GetType();
            if (string.Compare(_guidanceItem.Title, txtTitle.Text, true) != 0) 
            {
                //title changed
                return true;
            }
            
            if (_guidanceItem.CustomData.ContainsKey("Author"))
            {
                //author existed on the item - has it been changed?
                if (string.Compare(_guidanceItem.CustomData["Author"], txtAuthor.Text, true) != 0)
                {
                    return true;
                }
            }
            else if (!String.IsNullOrEmpty(txtAuthor.Text))
            {
                //author didn't exist before, but has been added
                return true;
            }

            if (htmlEditControl.HasChanged)
            {
                return true;
            }
            foreach (Field field in _guidanceItem.GuidanceType.Fields.Values)
            {
                //Skip non editable fields.
                if (!field.Editable)
                {
                    continue;
                }

                if (field.Name == "Author")
                {
                    //author is special case, don't check again
                    continue;
                }

                bool propertyFound = false;
                string value = null;

                //Create the textbox for the custom data value.
                if (field.Type == FieldType.Text)
                {
                    TextBox customData = tableLayoutPanel.Controls["txt" + field.Name] as TextBox;
                    value = customData.Text;
                }
                else if (field.Type == FieldType.Combo)
                {
                    ComboBox customData = tableLayoutPanel.Controls["txt" + field.Name] as ComboBox;
                    value = customData.Text;
                }
                else
                {
                    throw new NotImplementedException();
                }

                //Iterate through all the properties to see if there a property with the same name of the field.
                foreach (PropertyInfo property in guidanceItemType.GetProperties())
                {
                    if (property.Name == field.Name)
                    {
                        if (string.Compare((string)property.GetValue(_guidanceItem, null), value) != 0)
                        {
                            return true;
                        }
                        else
                        {
                            propertyFound = true;
                            break;
                        }
                    }
                }

                //If the property was not found, then set the custom data.
                if ((!propertyFound) && (_guidanceItem.CustomData.ContainsKey(field.Name)))
                {
                    if (string.Compare(_guidanceItem.CustomData[field.Name], value) != 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// Used to save the guidance
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!htmlEditControl.ValidateHtml(false) && (sender == btnSaveAs || ValidateTextBox(txtTitle, txtTitle.Text, "title")))
                {
                    Type guidanceItemType = _guidanceItem.GetType();
                    Form parent = Parent as Form;
                    //Set the title value.
                    _guidanceItem.Title = txtTitle.Text;
                    _guidanceItem.CustomData["Author"] = txtAuthor.Text;
                    //Update the text of the TreeNode.
                    if (_winFormsRenderService.GetGuidanceItemNode(_controller.TreeView, _guidanceItem) != null)
                        (_winFormsRenderService.GetGuidanceItemNode(_controller.TreeView, _guidanceItem)).Text = _guidanceItem.Title;

                    //Set the date
                    _guidanceItem.DateTime = DateTime.UtcNow;

                    if (IsValidCssPath(_txtCSS.Text))
                    {
                        //Set the CSS
                        _guidanceItem.CSSFile = _txtCSS.Text;
                    }

                    bool refreshView = false;

                    //If this is a new file, update the file path
                    if (!File.Exists(_guidanceItem.FullFileName))
                    {
                        #region Update File Path
                        string fileName = null;
                        if (_library != null)
                        {
                            string baseLibraryPath = null;
                            if (_library.ModelInstance.FileSubscribed)
                            {
                                baseLibraryPath = _library.ModelInstance.OriginalSourceFileInfo.DirectoryName + "\\" + _library.ModelInstance.Caption;
                                fileName = baseLibraryPath + "\\" + _guidanceItem.Id;
                            }
                            else
                            {
                                baseLibraryPath = Path.Combine(Path.Combine(ModelStorageService.LibraryFolder, _library.ModelInstance.Caption), _guidanceItem.GuidanceType.DisplayName);
                                fileName = Path.GetFullPath(Path.Combine(baseLibraryPath, _guidanceItem.Id));
                            }

                            if (!Directory.Exists(baseLibraryPath))
                            {
                                try
                                {
                                    Directory.CreateDirectory(baseLibraryPath);
                                }
                                catch (UnauthorizedAccessException)
                                {
                                    MessageBox.Show(Messages.ITEM_CANNOT_BE_SAVED_UNC_SHARE, Messages.ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }
                                catch (IOException)
                                {
                                    MessageBox.Show(Messages.ITEM_CANNOT_BE_SAVED_UNC_SHARE, Messages.ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }

                            }
                            else if (!_library.ModelInstance.FileSubscribed)
                            {
                            }
                        }
                        else //the item was created under the solution node. 
                        {
                            fileName = Path.Combine(_modelService.Guidance.SolutionViews.SolutionGuidanceFolder.FullName, _guidanceItem.Id);
                            //set item source
                            _guidanceItem[GuidanceItem.SourceField] = _modelService.Guidance.SolutionViews.SolutionName;
                        }
                        #endregion

                        _guidanceItem.FileName = fileName + ".xml";

                        refreshView = true;

                        //if (_view != null)
                        //{
                        //    _modelService.AddGuidanceItemToView(_view.ModelInstance, _guidanceItem);
                        //    _controller.AddGuidanceToTreeNode(_view, _guidanceItem);
                        //}
                        //if (_checkList != null)
                        //{
                        //    _modelService.AddGuidanceItemToCheckList(_checkList.ModelInstance, _guidanceItem);
                        //    _controller.AddGuidanceToTreeNode(_checkList, _guidanceItem);
                        //}
                    }

                    PopulateItemFields(guidanceItemType);

                    //Get the new Html
                    string newHtml = htmlEditControl.GetHtml();

                    //Add the item to the library
                    if (_library != null)
                    {
                        if (!_library.ModelInstance.Items.ContainsKey(_guidanceItem.Id))
                        {
                            _modelService.AddGuidanceItemToLibrary(_library.ModelInstance, _guidanceItem);
                            _guidanceItem.Library = _library.ModelInstance;
                        }
                        _winFormsRenderService.RefreshGuidanceTypeNodes(_library, _guidanceItem.GuidanceType);
                        _library.ModelInstance.HasChanges = true;
                    }
                    //Add the images
                    foreach (string img in htmlEditControl.NewImages)
                    {
                        _guidanceItem.AddImage(Path.GetFileName(img), img);
                    }
                    //Save the GuidanceItem
                    try
                    {
                        _modelService.RenderGuidanceItemToFileInfo(_guidanceItem, new FileInfo(_guidanceItem.FileName), newHtml);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        MessageBox.Show(Messages.ITEM_CANNOT_BE_SAVED_UNC_SHARE, Messages.ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    catch (IOException)
                    {
                        MessageBox.Show(Messages.ITEM_CANNOT_BE_SAVED_UNC_SHARE, Messages.ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    _exitHandled = true;

                    //// Copy ByVal to the solution
                    //GuidanceItemFileReference gitf = _modelService.CopyItemByValueToSolution(_guidanceItem);

                    //if (_view != null)
                    //{
                    //    _modelService.AddGuidanceItemToView(_view.ModelInstance, gitf);
                    //    _controller.AddGuidanceToTreeNode(_view, gitf);
                    //}
                    //if (_checkList != null)
                    //{
                    //    _modelService.AddGuidanceItemToCheckList(_checkList.ModelInstance, gitf);
                    //    _controller.AddGuidanceToTreeNode(_checkList, gitf);
                    //}

                    if (_view != null)
                    {
                        //if the item was saved to a library but the creation was invocated from a view under the solution node,
                        //copy also the item (by ref) to the view under the solution node
                        if (_library != null && _view.ModelInstance.CopyItemsByValue)
                        {
                            GuidanceItemFileReference gitf = _modelService.CopyItemByValueToSolution(_guidanceItem);
                            _modelService.AddGuidanceItemToView(_view.ModelInstance, gitf);
                            _controller.AddGuidanceToTreeNode(_view, gitf);
                        }
                        else
                        {
                            _modelService.AddGuidanceItemToView(_view.ModelInstance, _guidanceItem);
                            _controller.AddGuidanceToTreeNode(_view, _guidanceItem);
                        }
                    }
                    if (_checkList != null)
                    {
                        //if the item was saved to a library but the creation was invocated from a checklist under the solution node,
                        //copy also the item (by ref) to the checklist under the solution node
                        if (_library != null)
                        {
                            GuidanceItemFileReference gitf = _modelService.CopyItemByValueToSolution(_guidanceItem);
                            _modelService.AddGuidanceItemToCheckList(_checkList.ModelInstance, gitf);
                            _controller.AddGuidanceToTreeNode(_checkList, gitf);
                        }
                        else
                        {
                            _modelService.AddGuidanceItemToCheckList(_checkList.ModelInstance, _guidanceItem);
                            _controller.AddGuidanceToTreeNode(_checkList, _guidanceItem);
                        }
                    }
                                        
                    _controller.CloseToolWindow(_controller.FormatGuid(_originalItemId));

                    _controller.GuidanceItemOpened(this, new GuidanceItemFileReferenceEventArgs(new GuidanceItemFileReference[] { _guidanceItem },
                        ReadProtection.ReadOnly, _view, _checkList));

                    //Update the details UI
                    if (refreshView)
                    {
                        //select new item node
                        //if (_view != null)
                        //{
                        //    _controller.SelectNode(_view);
                        //    //TODO: refresh view if view's tool window is opened
                        //    //_controller.ViewNodeSelected(this, new ModelNodeEventArgs<GuidanceExplorer.Model.View>(_view));
                        //}
                        //else
                        //{
                        //    _controller.SelectNode(_library);
                        //    //TODO: refresh library if library's tool window is opened
                        //    //_controller.LibraryNodeSelected(this, new ModelNodeEventArgs<Library>(_library));
                        //}
                    }
                }
                else
                {
                    _exitHandled = false;
                }
            }
            catch (Exception ex)
            {
                _controller.HandleException(ex);
            }
        }

        private void PopulateItemFields(Type guidanceItemType)
        {
            foreach (Field field in _guidanceItem.GuidanceType.Fields.Values)
            {
                //Skip non editable fields.
                if (!field.Editable)
                {
                    continue;
                }
                //Skip the Author field
                if (field.Name == "Author")
                {
                    continue;
                }
                bool propertyFound = false;
                string value = null;

                //Create the textbox for the custom data value.
                if (field.Type == FieldType.Text)
                {
                    TextBox customData = tableLayoutPanel.Controls["txt" + field.Name] as TextBox;
                    value = customData.Text;
                }
                else if (field.Type == FieldType.Combo)
                {
                    ComboBox customData = tableLayoutPanel.Controls["txt" + field.Name] as ComboBox;
                    value = customData.Text;
                }
                else
                {
                    throw new NotImplementedException();
                }

                //Iterate through all the properties to see if there a property with the same name of the field.
                foreach (PropertyInfo property in guidanceItemType.GetProperties())
                {
                    if (property.Name == field.Name)
                    {
                        //If the property has been found, then set it's value.
                        property.SetValue(_guidanceItem, value, null);
                        propertyFound = true;
                        break;
                    }
                }

                //If the property was not found, then set the custom data.
                if (!propertyFound)
                {
                    if (_guidanceItem.CustomData.ContainsKey(field.Name))
                    {
                        _guidanceItem.CustomData[field.Name] = value;
                    }
                    else
                    {
                        _guidanceItem.CustomData.Add(field.Name, value);
                    }
                }

            }
        }

        private bool ValidateTextBox(Control control, string text, string fieldName)
        {
            if (String.IsNullOrEmpty(text) || text.Trim().Length == 0)
            {
                MessageBox.Show(string.Format(Messages.TITLE_EMPTY, fieldName), Messages.ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
                control.Focus();
                return false;
            }
            else
            {
                return true;
            }
        }

        private void btnSaveAs_Click(object sender, EventArgs e)
        {
            if (ValidateTextBox(txtTitle, txtTitle.Text, "title"))
            {
                LibrariesBrowser browser = new LibrariesBrowser();
                browser.NodeTypes = GuidanceNodeTypes.ReadWriteLibraries;
                browser.Guidance = _modelService.Guidance;
                if (browser.ShowDialog() == DialogResult.OK)
                {
                    _library = _winFormsRenderService.GetLibraryNodeByLibrary(_controller.TreeView, browser.SelectedLibrary);
                    _guidanceItem = _guidanceItem.Clone();
                    _guidanceItem.FileName = "";
                    btnSave_Click(btnSaveAs, e);
                }
            }
            else
            {
                _exitHandled = false;
            }
        }

        private void GuidanceItemMetadata_ParentChanged(object sender, EventArgs e)
        {
            if (ParentForm != null)
            {
                ParentForm.FormClosing += new FormClosingEventHandler(ParentForm_FormClosing);
            }
        }

        void ParentForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!_exitHandled)
            {
                e.Cancel = true;
                this.Show();
                btnCancel_Click(null, null);
            }
        }

        private void _txtCSS_Leave(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(_txtCSS.Text) && !IsValidCssPath(_txtCSS.Text))
            {
                MessageBox.Show(Messages.CSS_FILE_NOT_EXISTS, Messages.ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
                _txtCSS.Focus();
            }
            else
            {
                htmlEditControl.CSSPath = _txtCSS.Text;
            }
        }

        private static bool IsValidCssPath(string path)
        {
            return File.Exists(path) || File.Exists(Path.Combine(ModelStorageService.TemplateFolder, path));
        }

        private void btnCSSBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = Messages.CSS_FILES_FILTER;
            dialog.RestoreDirectory = true;
            dialog.CheckFileExists = true;
            dialog.CheckPathExists = true;
            dialog.Multiselect = false;

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                _txtCSS.Text = dialog.FileName;
            }
        }

    }
}
